package com.hxzy.controller;


import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.WebResource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;


/**
 * @author lzj
 * @create 2020-11-10 下午 3:47
 */
@Controller
public class UploadController {

    @ResponseBody
    @RequestMapping("/upload")
    public void upload(MultipartFile myfile, HttpServletRequest request) throws IOException {

        ServletContext servletContext = request.getSession().getServletContext();
        String realPath = servletContext.getRealPath("/upload");

        File file1 = new File(realPath,myfile.getOriginalFilename());

        myfile.transferTo(file1);
    }


    @ResponseBody
    @RequestMapping("/upload1")
    public String upload1(MultipartFile myfile, HttpServletRequest request) throws IOException {

        ServletContext servletContext = request.getSession().getServletContext();
        String realPath = servletContext.getRealPath("/upload");

        File file = new File(realPath,myfile.getOriginalFilename());

        myfile.transferTo(file);

        return "/upload/"+myfile.getOriginalFilename();
    }


    @ResponseBody
    @RequestMapping("/upload2")
    public String upload2(MultipartFile myfile, HttpServletRequest request) throws IOException {

//        设置图片服务器路径
        String path = "http://localhost:81/upload/" ;

//        获取文件名
        String filename = myfile.getOriginalFilename();

//       上传到图片服务器
//        创建上传客户端
        Client client = Client.create();
//      使用客户端连接图片服务器
        WebResource resource = client.resource(path + filename);
        resource.put(myfile.getBytes());
        return path+filename;
    }
}
